package com.mentalhealthplatform.teacherV2.controller;

import com.mentalhealthplatform.exception.permssion.PermissionNotFoundException;
import com.mentalhealthplatform.exception.user.UserAlreadyExistsException;
import com.mentalhealthplatform.global.debounce.Debounce;
import com.mentalhealthplatform.global.log.LogAction;
import com.mentalhealthplatform.global.log.login.LoginLogAction;
import com.mentalhealthplatform.global.rbac.dto.request.AuthRequest;
import com.mentalhealthplatform.global.rbac.dto.request.UserRegistrationRequest;
import com.mentalhealthplatform.global.rbac.dto.response.AuthResponse;
import com.mentalhealthplatform.global.rbac.model.User;
import com.mentalhealthplatform.global.rbac.service.entity.BaseUserService;
import com.mentalhealthplatform.utils.decryptUtils.field.DecryptFields;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v2/auth")
public class AuthControllerV2 {

    @Autowired
    private BaseUserService baseUserService;

    @PostMapping("/register")
    @LogAction(value = "register", description = "用户注册操作")
    public ResponseEntity<?> register(@RequestBody @DecryptFields @Valid UserRegistrationRequest registrationRequest, BindingResult bindingResult) {
        // 校验传入的数据
        if (bindingResult.hasErrors()) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", "VALIDATION_ERROR");
            response.put("message", bindingResult.getFieldError().getDefaultMessage());
            response.put("status", HttpStatus.BAD_REQUEST.value());
            response.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.badRequest().body(response);
        }

        try {
            // 调用 UserService 注册新用户
            User newUser = baseUserService.registerUser(registrationRequest);

            Map<String, Object> response = new HashMap<>();
            response.put("code", "SUCCESS");
            response.put("message", "用户注册成功");
            response.put("status", HttpStatus.CREATED.value());
            response.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(HttpStatus.CREATED).body(response);

        } catch (UserAlreadyExistsException ex) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", "USER_ALREADY_EXISTS");
            response.put("message", ex.getMessage());
            response.put("status", HttpStatus.CONFLICT.value());
            response.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(HttpStatus.CONFLICT).body(response);

        } catch (Exception ex) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", "INTERNAL_SERVER_ERROR");
            response.put("message", "服务器内部错误");
            response.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @PostMapping("/login")
    @LoginLogAction()
    public ResponseEntity<?> login(@RequestBody @DecryptFields @Valid AuthRequest authRequest, BindingResult bindingResult) {

        // 校验传入的数据
        if (bindingResult.hasErrors()) {
            // 抛出校验失败异常
            throw new BadCredentialsException("UNAUTHORIZED: 用户名或密码错误");
        }

        try {
            // 调用用户认证服务
            AuthResponse authResponse = baseUserService.authenticate(authRequest,"ROLE_TEACHER");
            return ResponseEntity.ok(authResponse);
        } catch (AuthenticationException e) {
            // 抛出认证失败异常
            throw new BadCredentialsException("UNAUTHORIZED: 用户名或密码错误");
        } catch (PermissionNotFoundException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", "USER_NOT_MATCH");
            response.put("message", e.getMessage());
            response.put("status", HttpStatus.UNAUTHORIZED.value());
            response.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }





}
